<?php

namespace App\Logic;

use App\Event\SmsSend;
use App\Exception\BusinessException;
use App\Model\SmsModel;
use App\Utils\SmsUtil;
use Hyperf\Di\Annotation\Inject;
use Psr\EventDispatcher\EventDispatcherInterface;

class SmsLogic
{
    /**
     * @var EventDispatcherInterface
     */
    #[Inject]
    private  $eventDispatcher;

    public function sendSms(string $mobile, string $event){
        $code = rand(1000, 9999);
        $smsRecord = SmsModel::create([
            'mobile' => $mobile,
            'event' => $event,
            'code' => $code
        ]);
        // 通过出发短信事件
        $this->eventDispatcher->dispatch(new SmsSend($smsRecord));
        return $code;
    }

    public function checkSms($mobile, $code, $event){
        //校验验证码
        $smsRecord = SmsModel::where([
            'mobile' => $mobile,
            'code' => $code,
            'event' => $event,
        ])->first();
        if(empty($smsRecord)){
            throw new BusinessException('验证码不正确');
        }
        if(time() - strtotime($smsRecord->created_at) > 600){
            throw new BusinessException('验证码已失效');
        }
        if($smsRecord->times >= 5){
            throw new BusinessException('验证码已失效');
        }
        $smsRecord->times ++;
        return $smsRecord->save();
    }
}